package com.fanly.weixin.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fanly.weixin.entity.Message;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class MessageUtils {
	/**
	 * 利用dom4j将请求流中的xml数据转换为map 方便后期分析数据
	 * @param is
	 * @return
	 * @throws DocumentException 
	 * @throws IOException 
	 */
	public static Map<String,String> toMap(InputStream is) throws DocumentException, IOException{
		//获取SaxReader
		SAXReader reader = new SAXReader();
		//获取文档
		Document doc = reader.read(is);
		//获取根元素
		Element root = doc.getRootElement();
		//获取其他元素
		List<Element> elements = root.elements();
		//遍历封装到Map中
		Map<String,String> map = new HashMap<String,String>();
		for(Element e: elements){
			map.put(e.getName(), e.getText());
		}
		is.close();
		return map;
	}
	/**
	 * 将map中的数据转换为Message对象
	 * @param map
	 * @return
	 */
	public static Message toMessage(Map<String,String> map){
		Message message = new Message();
		message.setContent(map.get("Content"));
		message.setCreateTime(Integer.valueOf(map.get("CreateTime")));
		message.setFromUserName(map.get("FromUserName"));
		message.setToUserName(map.get("ToUserName"));
		message.setMsgId(map.get("MsgId"));
		message.setMsgType(map.get("MsgType"));
		return message;
		
	}
	/**
	 * 将对象转为xml格式
	 * @param message
	 * @return
	 */
	public static String toXml(Message message){
		//实例化XStream
		XStream xStream = new XStream(new DomDriver());
		xStream.alias("xml", Message.class);
		String xml = xStream.toXML(message);
		return xml; 
	}
	/**
	 * 将map转为xml格式
	 * @param map
	 * @return
	 */
	public static String mapToXml(Map<String,String> map){
		//实例化XStream
		XStream xStream = new XStream(new DomDriver()); 
		xStream.alias("xml", Message.class);
		String xml = xStream.toXML(map);
		return xml; 
	}
	public static void main(String[] args) {
		Map<String,String> map = new HashMap<String,String>();
		map.put("content", "hello");
		map.put("type", "text");
		String xml = MessageUtils.mapToXml(map);
		System.out.println(xml);
	}
}
